import React, { useEffect, useState } from "react";
import {
  Card,
  Tree,
  Tag,
  Row,
  Col,
  Pagination,
  Table,
  Button,
  message,
} from "antd";
import { useNavigate, useParams } from "react-router-dom";
import {
  reqGetDepartmentsApi,
  reqGetScheduleRulesApi,
  reqGetScheduleListApi,
} from "@api/hospital";
import type {
  DepartmentsList,
  BookingScheduleList,
  ReqGetScheduleRulesParams,
  ScheduleList,
  ScheduleItem,
} from "@api/hospital/model/hospitalListType";
import type { ColumnsType } from "antd/es/table";

// 表格结构
const columns: ColumnsType<ScheduleItem> = [
  {
    width: 80,
    align: "center",
    title: "序号",
    render: (_, record, index) => index + 1,
  },
  {
    align: "center",
    title: "职称",
    dataIndex: "title",
  },
  {
    align: "center",
    title: "号源时间",
    dataIndex: "workDate",
  },
  {
    align: "center",
    title: "可预约数",
    dataIndex: "availableNumber",
  },
  {
    align: "center",
    title: "剩余预约数",
    dataIndex: "reservedNumber",
  },
  {
    align: "center",
    title: "挂号费(元)",
    dataIndex: "amount",
  },
  {
    align: "center",
    title: "擅长技能",
    dataIndex: "skill",
  },
];

export default function HospitalSchedule() {
  const { hoscode } = useParams();
  const navigate = useNavigate();

  // 医院科室列表
  const [departmentsList, setDepartmentsList] = useState<DepartmentsList>([]);
  // 控制医院科室列表默认展开的数据
  const [keyArr, setKeyArr] = useState<React.Key[]>([]);

  // 医院排班规则数据（Tag渲染的内容）
  const [scheduleRulesList, setScheduleRulesList] =
    useState<BookingScheduleList>([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(0);

  // 获取医院医生排班列表（table渲染的内容）
  const [workDate, setWorkDate] = useState("");
  const [depcode, setDepcode] = useState<React.Key>(0);
  const [schedlueList, setSchedlueList] = useState<ScheduleList>([]);

  // 路径导航相关
  const [depName, setDepName] = useState("");
  const [hospitalName, setHospitalName] = useState("");

  /*
    tree结构容器的自适应高度设置
    窗口高度 - Header组件高度（64） - Card的上下padding（24*2） - p元素的高度（22）和下外边距（14） - 防止纵向滚动条（5）
  */
  const treeHeight =
    document.body.getBoundingClientRect().height - 64 - 24 * 2 - 22 - 14 - 5;

  // 模拟挂载钩子
  useEffect(() => {
    async function fetch() {
      // 获取医院科室列表
      const initDepcode = await getDepartments(hoscode as string);
      // 医院科室没有数据，不再往下执行
      if (!initDepcode) {
        return;
      }
      // 获取医院排班规则（Tag渲染的数据）
      const initWorkDate = await getScheduleRulesList({
        page,
        limit: pageSize,
        hoscode: hoscode as string,
        // 页面初次挂载时，默认使用 多发性硬化专科门诊 的 depcode
        depcode: initDepcode as string,
      });
      // 获取医生排班表（table渲染的数据）
      getSchedlueList(initDepcode as string, initWorkDate);
    }
    fetch();
  }, []);

  // 分页器的回调
  async function onChangePage(page: number, pageSize: number) {
    setPage(page);
    setPageSize(pageSize);
    // 获取医院排班规则
    const WorkDate = await getScheduleRulesList({
      page,
      limit: pageSize,
      hoscode: hoscode as string,
      depcode,
    });
    // 获取医生排班列表
    getSchedlueList(depcode, WorkDate);
  }

  // 获取医院科室的排班规则（Tag渲染的内容）
  async function getScheduleRulesList({
    page,
    limit,
    hoscode,
    depcode,
  }: ReqGetScheduleRulesParams) {
    const res = await reqGetScheduleRulesApi({
      page,
      limit,
      hoscode,
      depcode,
    });
    // 初始化workDate
    const initWorkDate = `${
      // 当排班规则列表数据为空时，设置 workDate 的值为空串
      res.bookingScheduleList[0] ? res.bookingScheduleList[0].workDate : ""
    }`;
    setWorkDate(initWorkDate);
    setScheduleRulesList(res.bookingScheduleList);
    setTotal(res.total);
    setHospitalName(res.baseMap.hosname);
    return initWorkDate;
  }

  // 获取医院医生排班列表（table渲染的内容）
  async function getSchedlueList(depcode: React.Key, workDate: string) {
    const res = await reqGetScheduleListApi(
      hoscode as string,
      depcode,
      workDate
    );
    // 当科室有数据时，初始化 depName （路径导航的科室名称）
    if (res.length) {
      setDepName(res[0].param.depname);
    }
    setSchedlueList(res);
  }

  // 获取医院科室列表
  async function getDepartments(hoscode: string) {
    const res = await reqGetDepartmentsApi(hoscode);
    if (!res.length) {
      setDepcode("");
      message.error("当前科室暂无数据（只有多发性硬化专科门诊有数据）");
      return;
    }
    setKeyArr(res.map((item) => item.depcode));
    const newRes = res.map((item) => ({ ...item, disabled: true }));
    setDepartmentsList(newRes);
    // 页面初次渲染时，获取医院排班规则使用的 depcode
    const initDepcode = newRes[0].children[0].depcode;
    // 保存当前的 depcode
    setDepcode(initDepcode);
    return initDepcode;
  }

  // 选择科室
  async function onSelect(selectedKeys: React.Key[], info: any) {
    setDepcode(selectedKeys[0]);
    setDepName(info.node.depname);
    // 获取排班规则（Tag渲染的内容）
    const workDate = await getScheduleRulesList({
      page,
      limit: pageSize,
      hoscode: hoscode as string,
      depcode: selectedKeys[0],
    });
    if (!workDate) {
      message.error("当前科室暂无数据（只有多发性硬化专科门诊有数据）");
      setSchedlueList([]);
      return;
    }
    // 获取医生排班表（table渲染的内容）
    await getSchedlueList(selectedKeys[0], workDate);
  }

  // 选择排班日期（Tag按钮）
  function checkTag(workDate: string) {
    return async () => {
      getSchedlueList(depcode, workDate);
      setWorkDate(workDate);
      setPage(1);
    };
  }

  return (
    <Card>
      <div style={{ marginBottom: 10 }}>
        选择：
        {hospitalName} / {depName} / {workDate}
      </div>
      {/* 栅格 */}
      <Row gutter={20}>
        {/* 医院科室 */}
        <Col span={5}>
          <div
            style={{
              // width:200,
              border: "1px solid #ccc",
              height: treeHeight,
              overflow: "scroll",
              // float: "left",
            }}
          >
            <Tree
              expandedKeys={keyArr}
              onSelect={onSelect}
              treeData={departmentsList as []}
              // 自定义title和key
              fieldNames={{
                title: "depname",
                key: "depcode",
              }}
            />
          </div>
        </Col>
        <Col span={19}>
          <div>
            {scheduleRulesList.map((item, index) => (
              <Tag
                style={{ marginBottom: 10 }}
                color={`${workDate === item.workDate ? "success" : ""}`}
                key={index}
                onClick={checkTag(item.workDate)}
              >
                <div>{`${item.workDate} ${item.dayOfWeek}`}</div>
                <div>{`${item.availableNumber} / ${item.reservedNumber}`}</div>
              </Tag>
            ))}
          </div>
          <div style={{ marginBottom: 10 }}>
            <Pagination
              showSizeChanger
              onChange={onChangePage}
              defaultCurrent={3}
              total={total}
              current={page}
              pageSize={pageSize}
              pageSizeOptions={[5, 10, 15, 20]}
            />
          </div>
          <Table
            columns={columns}
            dataSource={schedlueList as []}
            rowKey={"id"}
            bordered
            pagination={false}
          />
          <Button
            style={{ marginTop: 10 }}
            onClick={() => {
              navigate("/syt/hospital/hospitallist");
            }}
          >
            返回
          </Button>
        </Col>
      </Row>
    </Card>
  );
}
